package com.coocaa.app.lib.cleaner.mgr.impl;

import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

import java.util.List;

/**
 * Created by Eric on 2017/7/8.
 */

public class CleanUtils {
    private static final int DELETE_TIME = 60;

//    interface CleanBack {
//        void CleanEnd(boolean success);
//    }
//
//    public static synchronized boolean handleScanAndAutoCleanWithBack(boolean cleanAppData, boolean needGeTime) {
//        final CountDownLatch lat = new CountDownLatch(1);
//        final MyObject<Boolean> mo = new MyObject(true);
//        handleScanAndAutoClean(new CleanBack() {
//            @Override
//            public void CleanEnd(boolean success) {
//                mo.set(success);
//                lat.countDown();
//            }
//        }, cleanAppData, needGeTime);
//        try {
//            lat.await();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return mo.get();
//    }
//
//    public static synchronized void handleScanAndAutoClean(final CleanBack mCleanBack, final boolean cleanAppData, final boolean needGeTime) {
//        try {
//            final Cleaner cleaner = CleanerManager.manager.instance(CoocaaApplication.getContext());
//            int tDay = 0;
//            if (needGeTime) {
//                tDay = cleaner.getServerCommand();
//                Log.d("autoclean", ">>>>>>>>>>>>>>>day:" + tDay);
//                if (tDay <= 0) {
//                    if (mCleanBack != null)
//                        mCleanBack.CleanEnd(false);
//                    return;
//                }
//            } else {
//                tDay = DELETE_TIME;
//            }
//            final int day = tDay;
//            cleaner.setCleanerListener(new Cleaner.CleanerListener() {
//
//                @Override
//                public void onScanStart() {
//                    Log.d("autoclean", ">>>>>>>>>>>>>>>onScanStart");
//                }
//
//                private Runnable cleanRunnable = new Runnable() {
//                    @Override
//                    public void run() {
//                        Log.d("autoclean", "????clean start!!!!!");
//                        long size = 0;
//                        size += cleaner.clearAllOtherData();
//                        size += cleaner.clearAllPackageCache();
//                        size += cleaner.clearAllApkRubbish();
//                        if (cleanAppData)
//                            size += cleaner.clearAllPackageData();
//                        cleaner.setOnAutoUninstallSuccessListener(new Cleaner.OnAutoUninstallSuccessListener() {
//                            @Override
//                            public void AutoUninstallSuccess(boolean success) {
//                                if (success) {
//                                    cleaner.resetCommandSuccess();
//                                    Log.i("AutoUninstallManager", " clean + inInstall 命令执行成功");
//                                }
//
//                            }
//                        });
//                        cleaner.unInstallApp(day);
//                        Log.d("autoclean", "????clean end!!!!!  " + size);
//                        if (mCleanBack != null)
//                            mCleanBack.CleanEnd(true);
//
//                    }
//                };
//
//                @Override
//                public synchronized void onScanEnd() {
//                    Log.d("autoclean", ">>>>>>>>>>>>>>>onScanEnd");
//                    AppCoreApplication.Companion.workerThread(new Function0<Unit>() {
//                        @Override
//                        public Unit invoke() {
//                            try {
//                                cleanRunnable.run();
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                            return Unit.INSTANCE;
//                        }
//                    });
//                }
//
//                @Override
//                public void onCleanAllStart() {
//
//                }
//
//                @Override
//                public void onCleanAllEnd(long size) {
//
//                }
//
//                @Override
//                public void onApkRubbishUpdate(DataHolder.ApkRubbish apkRubbish, String apkFile) {
////                    Log.d("autoclean", "{{onApkRubbishUpdate total:" + apkRubbish.size);
//                }
//
//                @Override
//                public void onPackageCacheUpdate(DataHolder.PackageCache packageCache, String packageName) {
////                    Log.d("autoclean", "{{onPackageCacheUpdate total:" + packageCache.size + "@" + packageName);
//                }
//
//                @Override
//                public void onPackageDataUpdate(DataHolder.PackageData packageData, String packageName) {
////                    Log.d("autoclean", "{{onPackageDataUpdate total:" + packageData.size + "@" + packageName);
//                }
//
//                @Override
//                public void onOtherDataUpdate(DataHolder.OtherData otherData, String file) {
////                    Log.d("autoclean", "{{onOtherDataUpdate total:" + otherData.size);
//                }
//            });
//            cleaner.startScan();
//        } catch (Exception e) {
//            e.printStackTrace();
//            if (mCleanBack != null)
//                mCleanBack.CleanEnd(false);
//        }
//        Log.d("autoclean", "~~~~~~~end ScanAndAutoClean");
//    }


//    private static boolean hasModule(Context context) {
//        PackageManager packageManager = context.getApplicationContext().getPackageManager();
//        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
//        List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
//                PackageManager.MATCH_DEFAULT_ONLY);
//        return list.size() > 0;
//    }

    private static UsageStats getUsageStats(Context context, String packageName) {
        if (Build.VERSION.SDK_INT >= 21) {
            long ts = System.currentTimeMillis();
            UsageStatsManager usageStatsManager = (UsageStatsManager) context.getApplicationContext().getSystemService(Context.USAGE_STATS_SERVICE);
            List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, ts - 200000, ts);
            if (queryUsageStats == null || queryUsageStats.isEmpty()) {
                return null;
            }
            for (UsageStats s : queryUsageStats) {
                if (s.getPackageName().equals(packageName))
                    return s;
            }
        }
        return null;
    }

    public static long getLastOpenTime(Context mContext, String pkg) {
        long time = -1;
        if (Build.VERSION.SDK_INT >= 21) {
            UsageStats stats = getUsageStats(mContext, pkg);
            if (stats != null) {
                time = stats.getLastTimeUsed();
                Log.i("AutoUninstallManager", "最后一次打开时间：" + time);
            } else {
                time = getLastInstallTime(mContext,pkg);
                Log.i("AutoUninstallManager", "安装时间： " + time);
            }
        }
        return time;
    }

    public static long getLastInstallTime(Context mContext, String packageName) {
        try {
            PackageManager pm = mContext.getPackageManager();
            PackageInfo info = pm.getPackageInfo(packageName, 0);
            return info.firstInstallTime;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }


//    public static synchronized void doClean(long fileSize) {
//        long freeDebug1 = getInternalFreeSpace();
//
//        long free = getInternalFreeWithResave();
//        boolean needClean = (free - fileSize * 3) > 0 ? false : true;
//        Log.i("autoclean", "doClean  free:" + free + " fileSize * 3:" + fileSize * 3 + " needClean:" + needClean);
//        if (needClean) {
//            boolean res = handleScanAndAutoCleanWithBack(false, false);
//            long freeDebug2 = getInternalFreeSpace();
//            Log.i("autoclean", "doClean  res:" + res);
//            //清完空间延迟一下去读空间，不然可能还是会报空间不足
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            long freeDebug3 = getInternalFreeSpace();
//
//            String l = "freeDebug1:%s\nfreeDebug2:%s\nfreeDebug3:%s\n";
//            Log.i("autoclean", String.format(l, freeDebug1, freeDebug2, freeDebug3));
//        }
//    }

//    private static long getInternalFreeWithResave() {
//        long free = getInternalFreeSpace();
//        long resave = getInternalTotalSpace() / 10;
//        return (free - resave) > 0 ? (free - resave) : 0;
//    }


//    /**
//     * 获取本机存储总容量
//     */
//    private static long getInternalTotalSpace() {
//        long blockSize = 0L;
//        long totalBlocks = 0L;
//        try {
//            File path = Environment.getDataDirectory();
//            StatFs stat = new StatFs(path.getPath());
//            blockSize = stat.getBlockSize();
//            totalBlocks = stat.getBlockCount();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return blockSize * totalBlocks;
//    }
//
//    /**
//     * 获取本机剩余存储空间
//     */
//    private static long getInternalFreeSpace() {
//        long blockSize = 0L;
//        long availableBlocks = 0L;
//        try {
//            File path = Environment.getDataDirectory();
//            StatFs stat = new StatFs(path.getPath());
//            blockSize = stat.getBlockSize();
//            availableBlocks = stat.getAvailableBlocks();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return blockSize * availableBlocks;
//    }


}
